const { Controller } = require('egg');

class OfficialBeerController extends Controller {
  async list() {
    const { ctx } = this;

    try {
      const token = ctx.request.header.authorization.replace('Bearer ', '');
      // 解码token
      const { open_id } = ctx.app.jwt.verify(token, 'beermaster');

      const detail = await ctx.service.userBeerWall.list({ open_id });
      ctx.body = {
        data: detail,
      };
    } catch (err) {
      ctx.body = { code: -1, error: err };
    }
  }

  async detail() {
    const { ctx } = this;
    const detail = await ctx.service.userBeerWall.detail(ctx.params.id);
    ctx.body = {
      code: 0,
      data: detail,
    };
  }

  async add() {
    const { ctx } = this;
    const { body } = ctx.request;

    const hadAdd = await ctx.service.userBeerWall.detail(body);
    if (hadAdd) {
      ctx.body = {
        code: -1,
        data: null,
        msg: '该酒已经添加过啦！',
      };
      return;
    }

    const detail = await ctx.service.userBeerWall.add(body);
    ctx.body = {
      code: 0,
      data: detail,
    };
  }
}

module.exports = OfficialBeerController;
